/**
 * projectName: mbzwb-parent
 * fileName: ShiroSessionManager.java
 * packageName: com.palmdoctor.mb.base.shiro
 * date: 2021-07-21 20:00
 * copyright(c) 2021 http://www.hydee.cn/ Inc. All rights reserved.
 */
package com.zny.sescore.shiro;


import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.SessionKey;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.session.mgt.WebSessionKey;

import javax.servlet.ServletRequest;
import java.io.Serializable;

@Slf4j
public class ShiroSessionManager extends DefaultWebSessionManager {
    /**
     * 获取session
     * 优化单次请求需要多次访问redis的问题
     *
     * @param sessionKey
     * @return
     * @throws UnknownSessionException
     */
    @Override
    protected Session retrieveSession(SessionKey sessionKey) throws UnknownSessionException {
        Serializable sessionId = getSessionId(sessionKey);
        log.info("sessionId={}", sessionId);
        ServletRequest request = null;
        if (sessionKey instanceof WebSessionKey) {
            request = ((WebSessionKey) sessionKey).getServletRequest();
        }

        if (request != null && null != sessionId) {
            Object sessionObj = request.getAttribute(sessionId.toString());
            if (sessionObj != null) {
                log.info("request get session={}", sessionObj);
                return (Session) sessionObj;
            }
        }

        Session session = super.retrieveSession(sessionKey);
        if (request != null && null != sessionId) {
            log.info("super  get session={}", session);
            request.setAttribute(sessionId.toString(), session);
        }
        return session;
    }

    @Override
    public void touch(SessionKey key) throws InvalidSessionException {
        Session session = doGetSession(key);
        if (session != null) {
            long oldTime = session.getLastAccessTime().getTime();
            session.touch(); // 更新访问时间
            long newTime = session.getLastAccessTime().getTime();
            // 如果两次访问的时间间隔大于5分钟，主动持久化Session
            if (newTime - oldTime > 2000) {
                onChange(session);
            }
        }
    }
}